import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.swing.JOptionPane;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class RemoteShellTool {
	  	public Connection conn;  
	    private String ipAddr;  
	    private String charset = Charset.defaultCharset().toString();  
	    private String userName;  
	    private String password;  
	    public static int port;
	    
	    public RemoteShellTool(String ipAddr, String userName, String password,  
	            String charset) {  
	        this.ipAddr = ipAddr;  
	        this.userName = userName;  
	        this.password = password;  
	        if (charset != null) {  
	            this.charset = charset;  
	        }  
	    }  
	    
	    public boolean login() throws IOException {  
	        conn = new Connection(ipAddr, port);  
	        conn.connect(); // 连接  
	        return conn.authenticateWithPassword(userName, password); // 认证  
	    }  
	    
	    public String exec(String cmds) {  
	        InputStream in = null;  
	        String result = ""; 
	        Session session = null;
	        boolean flag = false;
	        try {  
	        	if(this.login()){
	        		session = conn.openSession(); // 打开一个会话  
	        		session.execCommand(cmds);  
	        		in = session.getStdout();  
	        		result = this.processStdout(in, this.charset);  
	        		session.close();  
	        		conn.close(); 
	        		flag = true;	            
	        	}
	        } catch (IOException e1) {  
	            e1.printStackTrace();  
	            JOptionPane.showMessageDialog(null, "执行失败:"+e1.getMessage(),"提示", JOptionPane.INFORMATION_MESSAGE);
	        } finally {
	        	if(session != null){
	        		session.close();
	        	}
	        }
	        return result;  
	    }  
	    
	    public String processStdout(InputStream in, String charset) {  
	      
	        byte[] buf = new byte[1024];  
	        StringBuffer sb = new StringBuffer();  
	        try {  
	            while (in.read(buf) != -1) {  
	                sb.append(new String(buf, charset));  
	            }  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	        return sb.toString();  
	    }  
	  
}